package com.dict.servlets;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.dict.classes.User;
import com.dict.process.AddUserProcess;
import com.dict.process.AddWordProcess;
import com.dict.process.DelWordProcess;
import com.dict.process.DelUserProcess;

public class WordServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doPost(HttpServletRequest request,
	                    HttpServletResponse response)
	      throws ServletException, IOException {
	    
		String strUsername = request.getParameter("username");
		String strPassword = request.getParameter("password");	    
	    String strAction = request.getParameter("action");
		
		HttpSession session = request.getSession();
		
	    if (strAction.equals("newWord"))
	    {
		    AddWordProcess process = new AddWordProcess();
		    try
		    {
		    	process.doProcess(request, response);
		    }
		    catch (Exception E)
		    {
		    	E.printStackTrace();
		    }
	    }
	    if (strAction.equals("delWord"))
	    {
		    DelWordProcess process = new DelWordProcess();
		    try 
		    {
		    	process.doProcess(request, response);
		    }
		    catch (Exception E)
		    {
		    	E.printStackTrace();
		    }
	    }
	    if(strAction.equals("newUser")){
	    	AddUserProcess process = new AddUserProcess();
	    	try {
				process.doProcess(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
	    }
	    if(strAction.equals("delUser")){
	    	DelUserProcess process = new DelUserProcess();
	    	try {
				process.doProcess(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
	    }
	    if(strAction.equals("login")){
	    	User user = new User();
			user.setUsername(strUsername);
			user.setPassword(strPassword);

			int userId = -1;
			try {
				userId = user.authenticateUser();
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			
			if(userId != -1)
			{
				user.setId(userId);
				session.setAttribute("authUser", user);
				response.sendRedirect("index.jsp");
			}
	    }
	    if(strAction.equals("logout")){
	    	logout(response, session);
	    }
	  }

	private void logout(HttpServletResponse response, HttpSession session)
			throws IOException {
		session.invalidate();
		response.sendRedirect("login.jsp");
	}
	
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
		
	}
}